package cn.itcast.n8;

import cn.itcast.n2.util.Sleeper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author: AirMan
 * @date: 2025/4/22 18:25
 * @description:
 */
@Slf4j(topic = "c.TestForkJoin_My")
public class TestForkJoin_My {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ForkJoinPool forkJoinPool = new ForkJoinPool(4);

        Integer result = forkJoinPool.invoke(new MyForkJoinTask(5));

        System.out.println("result = " + result);

    }

    static class MyForkJoinTask extends RecursiveTask<Integer> {

        private int n;

        public MyForkJoinTask(int n) {
            this.n = n;
        }

        @SneakyThrows
        @Override
        protected Integer compute() {
            // 0.递归的终止条件
            if (n == 1) {
                log.debug("递归终止！");
                return 1;
            }

            // 1.下一个线程执行的内容
            MyForkJoinTask nextTask = new MyForkJoinTask(n - 1);
            log.debug("{} + compute({})", n, n - 1);
            // 2.执行下一个线程
            nextTask.fork();
            TimeUnit.MILLISECONDS.sleep(100);   // 让线程执行完成的速度慢一些
            // 3.等待线程返回结果
            return n + nextTask.join();
        }
    }
}
